import React, { useEffect, useState } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Space,
  message,
  Popconfirm,
} from "antd";
import {
  getUserListApi,
  addUserApi,
  editUserApi,
  deleteUserApi,
} from "@/apis/userManage";

const { Option } = Select;

const UserManage: React.FC = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [data, setData] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);
  const [sorter, setSorter] = useState<any>({});
  const [passwordTouched, setPasswordTouched] = useState(false);

  // 获取用户列表
  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      const res: any = await getUserListApi({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...searchForm.getFieldsValue(),
        ...params,
        ...sorter,
      });
      if (res.code === 0) {
        setData(res.data);
        setPagination({
          ...pagination,
          current: res.data.page,
          pageSize: res.data.pageSize,
          total: res.data.total,
        });
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, sorter]);

  // 搜索
  const onSearch = () => {
    setPagination({ ...pagination, current: 1 });
    fetchData({ page: 1 });
  };

  // 新增/编辑
  const onFinish = async (values: any) => {
    try {
      if (editingUser) {
        console.log(1);
        
        await editUserApi({ ...values, ID: editingUser.ID });
        message.success("编辑成功");
      } else {
        console.log(2);
        
        await addUserApi(values);
        message.success("新增成功");
      }
      setModalVisible(false);
      fetchData();
      form.resetFields();
      setEditingUser(null);
    } catch {
      message.error("操作失败");
    }
  };

  // 删除
  const onDelete = async (id: string) => {
    try {
      await deleteUserApi(id);
      message.success("删除成功");
      fetchData();
    } catch {
      message.error("删除失败");
    }
  };

  // 打开编辑
  const openEdit = (record: any) => {
    setEditingUser(record);
    setModalVisible(true);
    setPasswordTouched(true);
    setTimeout(() => {
      form.setFieldsValue({ ...record, password: "" });
    }, 0);
  };

  // 打开新增
  const openAdd = () => {
    setEditingUser(null);
    setModalVisible(true);
    setPasswordTouched(false);
    setTimeout(() => {
      form.resetFields();
      form.setFieldsValue({ password: "", status: "active", role: "user", email: "" });
    }, 0);
  };

  // 监听邮箱变化
  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const email = e.target.value;
    if (!passwordTouched) {
      form.setFieldsValue({ password: email });
    }
  };

  // 监听密码输入
  const handlePasswordChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setPasswordTouched(true);
  };

  // 表格排序
  const handleTableChange = (_: any, __: any, sorterObj: any) => {
    if (sorterObj.order) {
      setSorter({ sortField: sorterObj.field, sortOrder: sorterObj.order });
    } else {
      setSorter({});
    }
  };

  const columns = [
    { title: "用户名", dataIndex: "username", sorter: true },
    { title: "邮箱", dataIndex: "email", sorter: true },
    { title: "角色", dataIndex: "role", sorter: true },
    {
      title: "状态",
      dataIndex: "status",
      render: (v: string) => (v === "active" ? "正常" : "禁用"),
    },
    {
      title: "操作",
      render: (_: any, record: any) => (
        <Space>
          <Button type="link" onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗？"
            onConfirm={() => onDelete(record.ID)}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Form
        layout="inline"
        form={searchForm}
        onFinish={onSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="username" label="用户名">
          <Input placeholder="搜索用户名" />
        </Form.Item>
        <Form.Item name="email" label="邮箱">
          <Input placeholder="搜索邮箱" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={openAdd} type="primary">
            新增用户
          </Button>
        </Form.Item>
      </Form>
      <Table
        rowKey="ID"
        columns={columns}
        dataSource={data}
        loading={loading}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) =>
            setPagination({ ...pagination, current: page, pageSize }),
        }}
        onChange={handleTableChange}
      />
      <Modal
        title={editingUser ? "编辑用户" : "新增用户"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        destroyOnClose
        centered
      >
        <Form
          form={form}
          onFinish={onFinish}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 18 }}
          initialValues={{ status: "active", role: "user" }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "邮箱格式不正确" },
            ]}
          >
            <Input onChange={handleEmailChange} />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Select>
              <Option value="admin">管理员</Option>
              <Option value="user">普通用户</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: "请选择状态" }]}
          >
            <Select>
              <Option value="active">正常</Option>
              <Option value="disabled">禁用</Option>
            </Select>
          </Form.Item>
          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[
                { required: true, message: "请输入密码" },
                { min: 6, message: "密码至少6位" },
              ]}
            >
              <Input.Password placeholder="请输入密码" onChange={handlePasswordChange} />
            </Form.Item>
          )}
        </Form>
      </Modal>
    </div>
  );
};

export default UserManage;
